package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.service.MemberService;
import com.itheima.health.service.OrderService;
import com.itheima.health.service.ReportService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.annotation.Reference;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 数据报告控制器
 */
@RestController
@RequestMapping("/report")
@Slf4j
@Api(tags = "数据报告展示接口")
public class ReportController {
    @Autowired
    private OrderService orderService;

    /**
     * 套餐占比统计
     */
    @GetMapping("/getSetmealReport")
    public Result getSetmealReport() {
        List<Map<String, Object>> list = orderService.countBySetMeal();

        HashMap<Object, Object> map = new HashMap<>();
        map.put("setmealCount", list);

        ArrayList<String> setmealNames = new ArrayList<>();
        for (Map<String, Object> m : list) {
            String name = (String) m.get("name");
            setmealNames.add(name);
        }
        map.put("setmealNames", setmealNames);

        return new Result(true, MessageConst.GET_SETMEAL_COUNT_REPORT_SUCCESS, map);
    }

    @Autowired
    private MemberService memberService;


    @Autowired
    private ReportService reportService;

    @GetMapping("/getBusinessReportData")
    public Result getBusinessReportData() {
        Map<String, Object> map = reportService.getBusinessReportData();
        return new Result(true, MessageConst.GET_BUSINESS_REPORT_SUCCESS, map);
        }
    @GetMapping("getMemberReport")
    @Cacheable( cacheNames = "memberReportCache")
    public Result getMemberReport () {
        log.info("统计分析会员数量,当前时间:{}", new Date());
        Map<String, List<String>> map = reportService.getMemberReport();
        return new Result(true, MessageConst.UPLOAD_SUCCESS, map);
    }

    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response)  {


        //远程调用报表服务获取报表数据
        Map<String, Object> resultMap = reportService.getBusinessReportData();
        //取出返回结果数据，准备将报表数据写入到Excel文件中
        String reportDate = (String) resultMap.get("reportDate");
        Long todayNewMember = (Long) resultMap.get("todayNewMember");
        Long totalMember = (Long) resultMap.get("totalMember");
        Long thisWeekNewMember = (Long) resultMap.get("thisWeekNewMember");
        Long thisMonthNewMember = (Long) resultMap.get("thisMonthNewMember");
        Long todayOrderNumber = (Long) resultMap.get("todayOrderNumber");
        Long thisWeekOrderNumber = (Long) resultMap.get("thisWeekOrderNumber");
        Long thisMonthOrderNumber = (Long) resultMap.get("thisMonthOrderNumber");
        Long todayVisitsNumber = (Long) resultMap.get("todayVisitsNumber");
        Long thisWeekVisitsNumber = (Long) resultMap.get("thisWeekVisitsNumber");
        Long thisMonthVisitsNumber = (Long) resultMap.get("thisMonthVisitsNumber");
        List<Map> hotSetmeal = (List<Map>) resultMap.get("hotSetmeal");



        try {
//            String filePath = request.getSession().getServletContext().getRealPath("resources/report_template.xlsx");
            //获得Excel模板文件绝对路径
             InputStream is = this.getClass().getClassLoader().getResourceAsStream("report_template.xlsx");

            //读取模板文件创建Excel表格对象
            XSSFWorkbook excel = new XSSFWorkbook(is);
            //读取excel文件中第一个sheet标签页
            XSSFSheet sheet = excel.getSheetAt(0);
            //获取第三行
            XSSFRow row = sheet.getRow(2);
            //报表日期
            row.getCell(5).setCellValue(reportDate);

            //第五行
            row = sheet.getRow(4);
            //新增会员数
            row.getCell(5).setCellValue(todayNewMember);
            //总会员数
            row.getCell(7).setCellValue(totalMember);

            //第六行
            row = sheet.getRow(5);
            //本周新增会员数
            row.getCell(5).setCellValue(thisWeekNewMember);
            //本月新增会员数
            row.getCell(7).setCellValue(thisMonthNewMember);

            //第八行
            row = sheet.getRow(7);
            //今日预约数
            row.getCell(5).setCellValue(todayOrderNumber);
            //今日到诊数
            row.getCell(7).setCellValue(todayVisitsNumber);

            //第九行
            row = sheet.getRow(8);
            //本周预约数
            row.getCell(5).setCellValue(thisWeekOrderNumber);
            //本周到诊数
            row.getCell(7).setCellValue(thisWeekVisitsNumber);

            //第十行
            row = sheet.getRow(9);
            //本月预约数
            row.getCell(5).setCellValue(thisMonthOrderNumber);
            //本月到诊数
            row.getCell(7).setCellValue(thisMonthVisitsNumber);

            //热门套餐
            int rowNum = 12;
            for (Map map : hotSetmeal) {
                String name = (String) map.get("name");//套餐名字
                Long setmeal_count = (Long) map.get("setmeal_count");//套餐预约数量
                BigDecimal proportion = (BigDecimal) map.get("proportion");//占比
                row = sheet.getRow(rowNum++);
                row.getCell(4).setCellValue(name);//套餐名字
                row.getCell(5).setCellValue(setmeal_count);//套餐预约数量
                row.getCell(6).setCellValue(proportion.doubleValue());//占比  Double的取值必须用doubleValue()
            }
            //使用输出流进行文件下载，(基于浏览器作为客户端)
            OutputStream out = response.getOutputStream();

            //设置excel文件类型
            response.setContentType("application/vnd.ms-excel");
            //以附件形式进行下载
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");

            //写
            excel.write(out);

            //刷新
            out.flush();

            //释放
            out.close();
            excel.close();

            return null;
        } catch (Exception e) {
            //显示try里面哪个代码异常
            e.printStackTrace();
                return new Result(false,MessageConst.GET_BUSINESS_REPORT_FAIL);
        }
    }
}
